<?php
class Activity_Model extends Model {
	/**
	 * Master logging method
	 */
	public function log_activity($params)
	{
		$cur_user = $this->userland->current_user();
		$actor_id = ($cur_user === false) ? -1 : $cur_user->id;
		
		$params['actor_id'] 	= $actor_id;
		$params['created_at']	= mysql_now();
		if (isset($params['extra']))
		{
			$params['extra_data'] = $params['extra'];
			unset($params['extra']);
		}
		
		$this->db->insert('activity_stream', $params);
	}
	
	/**
	 * Wrappers
	 */
	public function log_comment($params)
	{
		$params['action'] 			= "commented";
		$params['activity_type'] 	= "profile_comment";
		//$params['full_string']		= "{$params['subject']} commented on {$params['object']}'s profile";
		$this->log_activity($params);
	}
	
	public function log_tag($params)
	{
		$params['action'] 			= "tagged";
		$params['activity_type'] 	= "add_tag";
		//$params['full_string']		= "{$params['subject']} tagged {$params['object']}";
		$this->log_activity($params);
	}
	
	public function log_content_comment($params)
	{
		$params['action'] 			= "commented";
		$params['activity_type'] 	= "content_comment";
		$this->log_activity($params);
	}
	
	/**
	 * Loaders
	 */
	
	// $scope is an array of WHERE parameters
	public function get_activity($scope = array())
	{
		if (isset($scope['contacts_of']))
		{
			$conid = $scope['contacts_of'];
			$filter_to_user_contacts = $this->db->query("SELECT followed_user_id FROM followers WHERE user_id = ?",
				$conid);
		}
		else
			$filter_to_user_contacts = false;
			
		unset($scope['contacts_of']);
			
		if ($filter_to_user_contacts && !$filter_to_user_contacts->num_rows())
		{
			$filter_to_user_contacts = false;
			return false;
		}
		
		if (!empty($scope))
			$this->db->where($scope);
			
		if ($filter_to_user_contacts)
		{
			// Add an actor_id IN (...)
			$filter_to_user_contacts_ary = array();
			foreach ($filter_to_user_contacts->result() as $res)
				$filter_to_user_contacts_ary[] = $res->followed_user_id;
				
			if (count($filter_to_user_contacts))
			{
				
				if (count($scope))
				{
					foreach ($scope as $k => $v)
					{
						if ($k != 'contacts_of')
							$_scope[] = "{$k} = {$v}";
					}
						
					$_scope = ' AND ' . join(' AND ', $_scope);
				}
				else
				{
					$_scope = '';
				}
				
				$query = $this->db->query("SELECT * FROM activity_stream
				WHERE
					actor_id IN (".join(',', $filter_to_user_contacts_ary).")
					{$_scope}
				ORDER BY created_at DESC
				LIMIT 15");
			}
		}
		else
		{	
			$this->db->select('*');
			$this->db->order_by('created_at desc');
			$this->db->limit(15);
		
			$query = $this->db->get('activity_stream');
		}
		
		if ($query->num_rows())
			return $query;
		else
			return false;
	}
}
?>